//
//  deskViewController.m
//  BeautyPicture
//
//  Created by 沈振邦 on 15/7/27.
//  Copyright (c) 2015年 szb. All rights reserved.
//

#import "BPProductMakeViewController.h"
#import "keyboardView.h"
//#import "BPProductShareViewController.h"
#import "AppDelegate.h"
#import "HMSegmentedControl.h"
#import "MBProgressHUD+MJ.h"
#import "UIViewController+MJPopupViewController.h"
#import "BPImageTool.h"
#import "ImageEditView.h"
#import "NavView.h"
#import "AccountTool.h"
#import "MJExtension.h"
#import "AFNetworking.h"
//#import <CoreTelephony/CTTelephonyNetworkInfo.h>
#import "BPLoginViewController.h"
#import "BPhttpTool.h"
#import "UIColor+Extension.h"
#import "QiniuSDK.h"
#import "SDWebImageManager.h"
#import "orderDetailVC.h"
#import "ImageView.h"


#define ImageCahes [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]

#define PI 3.14159265358979323846264338327950288 * 2.0
#define buttomH 40.0f
#define buttomToolH 70.0f

@interface BPProductMakeViewController ()<navDelegate,UITextFieldDelegate,customToolBarDelegate,ZYQAssetPickerControllerDelegate,UINavigationControllerDelegate,BPkeyboardToolBarDelegate,BPkeyboardDelegate,BPCustomViewDelegate,BPCustomLabelDelegate>
{
    MBProgressHUD *_postHud;
}

//判断是否是键盘
@property (nonatomic,assign)BOOL isKeyboard;

@property (nonatomic,strong)UIView *currentView;

@property (nonatomic,strong)UIView *topCurView;

@property (nonatomic,strong)UIView *btnView;

//判断是否正在上传
@property (nonatomic,assign)BOOL isPost;

//判断那几张图片没点
@property (nonatomic,strong)NSMutableArray *diyImageTotal;

@property (nonatomic,assign)NSInteger clickNO;
//当前点中的scrollview
@property (nonatomic,assign) NSInteger cviewIndex;

@property (nonatomic, assign) NSInteger diWenIndex;

@property (nonatomic, assign) NSInteger beijingIndex;

//用来对 当前 页面 修改后 的保存
@property (nonatomic,strong)BPProductDetailPage *pageInfo;
//高亮显示label
@property (nonatomic, strong) UILabel *labelHeilight;
@property (nonatomic, strong) UILabel *labelName;

@property (nonatomic, strong) UIImageView *ima;
@property (nonatomic, strong) UIImageView *imb;
@property (nonatomic, strong) UIImageView *imc;
@property (nonatomic, strong) UIImageView *imd;

@property (nonatomic, strong) UILabel *labA;
@property (nonatomic, strong) UILabel *labB;
@property (nonatomic, strong) UILabel *labC;
@property (nonatomic, strong) UILabel *labD;


// (模板) 放在图片上的 文字
@property (nonatomic, strong) UILabel *label;

// (底纹) label
@property (nonatomic, strong) UILabel *labelDiWen;

// (背景) label
@property (nonatomic, strong) UILabel *BeijingLabel;

@end

@implementation BPProductMakeViewController



- (void)viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBarHidden = YES;
//    self.navigationController.navigationBarHidden = NO;
//    [D_Main_Appdelegate hiddenPreView];
    [self buttomTableViewappear:_mubanView setY:buttomToolH + buttomH];
   
    
    // 键盘即将弹出, 就会发出UIKeyboardWillShowNotification
    [self setUpNotice];
    
}

- (void)viewWillDisappear:(BOOL)animated
{
    self.navigationController.navigationBarHidden = NO;

    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
        
    // 通过 滑动手势, 让键盘隐藏
    UISwipeGestureRecognizer *swipe = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipe:)];
    [self.view addGestureRecognizer:swipe];
    // 滑动 手势的 方向 ()向下
    swipe.direction = UISwipeGestureRecognizerDirectionDown;
    
    [self setUpNavgation];
    //1.配置UI数据
    [self setUpUIData];

    [self drawUIView];
    
    [self createButton];
    self.cviewIndex = 0;
    self.diWenIndex = 0;
    self.beijingIndex = 0;
}



// 滑动手势的 实现方法
- (void)swipe:(UISwipeGestureRecognizer *)swipe
{
    
    self.labB.textColor = [UIColor whiteColor];
    self.labC.textColor = [UIColor whiteColor];
    self.labD.textColor = [UIColor whiteColor];
    self.labA.textColor = BPFenHongColor;
    
    self.imb.image = [UIImage imageNamed:@"diwen"];
    self.imc.image = [UIImage imageNamed:@"beijing"];
    self.imd.image = [UIImage imageNamed:@"moBan"];
    self.ima.image = [UIImage imageNamed:@"moban-over"];
    
    [self zidingyiJIanpanDisappear];
    [self buttomTableViewDisappear];
    [self buttomTableViewappear:_mubanView setY:buttomToolH + buttomH];
}

// 创建 返回按钮
- (void)createButton{
    self.view.backgroundColor = BPHuiColor;
    UIButton *buttonBig = [[UIButton alloc] initWithFrame:CGRectMake(20, 25, 80, 50)];
    buttonBig.backgroundColor = [UIColor clearColor];
    [buttonBig addTarget:self action:@selector(button:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:buttonBig];
    
    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 23, 23)];
    [button setBackgroundImage:[UIImage imageNamed:@"返回"] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(button:) forControlEvents:UIControlEventTouchUpInside];
    [buttonBig addSubview:button];
    
//    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(20, 25, 23, 23)];
//    [button setBackgroundImage:[UIImage imageNamed:@"返回"] forState:UIControlStateNormal];
//    [button addTarget:self action:@selector(button:) forControlEvents:UIControlEventTouchUpInside];
//    [self.view addSubview:button];
    
    UIButton *buttonSave = [[UIButton alloc] initWithFrame:CGRectMake(self.view.frame.size.width - 40, 30, 50, 50)];
    buttonSave.backgroundColor = [UIColor clearColor];
    [buttonSave addTarget:self action:@selector(saveDIYImage) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:buttonSave];
    
    UIButton *buttonHome = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 23, 23)];
    [buttonHome setBackgroundImage:[UIImage imageNamed:@"save"] forState:UIControlStateNormal];
    [buttonHome addTarget:self action:@selector(saveDIYImage) forControlEvents:UIControlEventTouchUpInside];
    [buttonSave addSubview:buttonHome];
    
    
    self.labelName = [[UILabel alloc] initWithFrame:CGRectMake(self.view.frame.size.width / 2 - 30, 20, 100, 40)];
    self.labelName.font = [UIFont systemFontOfSize:20];
    self.labelName.textColor = BPFenHongColor;
    self.labelName.text = @"第1页";
    [self.view addSubview:self.labelName];

    
    
    
}
//// 头部的 两个按钮
//- (void)button:(UIButton *)b{
//    [self.navigationController popViewControllerAnimated:YES];
//}
// 头部的 两个按钮
- (void)button:(UIButton *)b{
    
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"您的作品马上要完成啦,想现在就放弃吗?" delegate:self cancelButtonTitle:@"稍后完成" otherButtonTitles:@"继续完成", nil];
    [alert show];
    
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 0) {
        [self.navigationController popViewControllerAnimated:YES];
    }
    else{
        [alertView removeFromSuperview];
    }
}


- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)setUpNotice
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    // 键盘即将隐藏, 就会发出UIKeyboardWillHideNotification
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}

#pragma - mark 隐藏view操作
- (void)hidebackView
{
//    [self buttomTableViewDisappear];
}

#pragma mark - 设置导航栏
- (void)setUpNavgation
{
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"保存/分享" style:UIBarButtonItemStyleDone target:self action:@selector(saveDIYImage)];
    NavView *leftNavView = [[NavView alloc] initWithFrame:CGRectMake(0, 0, 70, 40)];
    leftNavView.navLabel.text = self.productInfo.category;
    if (_isFirst == NO) {
        leftNavView.navLabel.text = @"我的作品";
    }
    leftNavView.delegate = self;
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftNavView];
}




//下载底纹和背景色
- (void)DownloadShadingAndBackcolor
{
    [BPhttpTool get:[NSString stringWithFormat:@"%@appapi/getmaterial/type/1",BPhttp] params:nil success:^(id responseObj) {
        _shadingArry = responseObj;
        [_shadingScrollview reloadData];
        [[NSUserDefaults standardUserDefaults] setObject:_shadingArry forKey:@"shading"];
         [[NSUserDefaults standardUserDefaults] synchronize];
        
    } failure:^(NSError *error) {
        BPLog(@"获取底纹失败");
    }];

    [BPhttpTool get:[NSString stringWithFormat:@"%@appapi/getmaterial/type/2",BPhttp] params:nil success:^(id responseObj) {
        _colorArry = responseObj;
        [_bgColorScrollview reloadData];
        
        [[NSUserDefaults standardUserDefaults] setObject:_colorArry forKey:@"backColor"];
        [[NSUserDefaults standardUserDefaults] synchronize];
        
    } failure:^(NSError *error) {
        BPLog(@"获取背景色失败");
    }];
}

- (void)saveDIYImage
{
    //1.保存没有diy过的照片到本地
    [_imagePaths replaceObjectAtIndex:_pageNumber withObject:[self saveDiyImageToCaches]];
    //保存配置信息
    [_userEnableView savePageInfo:self.productInfo.pages[_pageNumber]];
    
    [self removeArryObject];
    
    //2.判断那几张没有编辑
    if (self.clickNO != 0) {
        NSString *str = [self.diyImageTotal componentsJoinedByString:@" "];
        NSString *prompt = [NSString stringWithFormat:@"%@尚未编辑,请继续编辑",str];
        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"提示" message:prompt delegate:nil cancelButtonTitle:@"好的" otherButtonTitles:nil, nil];
        [alert show];
    }else{
        //判断有没有uid
        if ([AccountTool account].uid != nil) {
            
            self.productInfo.uid = [AccountTool account].uid;
            //有uid就进行上传照片
            [self makeOrderAndPostImage];
        }else{
            [[NSNotificationCenter defaultCenter] removeObserver:self];
            BPLoginViewController *loginAPP = [[BPLoginViewController alloc] init];
            [self.navigationController pushViewController:loginAPP animated:YES];
            loginAPP.block = ^(){
               [[NSNotificationCenter defaultCenter] removeObserver:self];
               [self makeOrderAndPostImage];
            };
        }
    }    
}

- (void)saveProductTocoreData
{
    if (self.productInfo.makeDate == nil) {
        //设置时间戳
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
        NSString *timeTamp = [formatter stringFromDate:[NSDate date]];
        self.productInfo.makeDate = timeTamp;
        [MyproductManger saveADIYproduct:self.productInfo];
    }else{
        [MyproductManger updateADIYproduct:self.productInfo];
    }
    
}

- (void)makeOrderAndPostImage
{
    _postHud = [MBProgressHUD showMessage:@"正在上传"];
    //1.请求workid
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic setValue:self.productInfo.iD forKey:@"product_id"];
    [dic setValue:[AccountTool account].uid forKey:@"uid"];
    if (self.productInfo.workID == nil) {
        [BPhttpTool post:[NSString stringWithFormat:@"%@works/saveWorks",BPhttp] params:dic success:^(id responseObj) {
            //1.获取workID
            NSString *workID = responseObj[@"info"];
            self.productInfo.workID = workID;
            
            //2.上传生成好的小图
            [self uploadThumpPicture];
            
        } failure:^(NSError *error) {
            [MBProgressHUD hideHUD];
            [MBProgressHUD showError:@"上传失败"];
        }];
    }else{
        [self uploadThumpPicture];
    }
   
}

- (void)uploadThumpPicture{
    [self saveProductTocoreData];
    NSMutableArray *pages = [NSMutableArray array];
    [BPhttpTool get:[NSString stringWithFormat:@"%@Upload/get_qiniu_token",BPhttp] params:nil success:^(id responseObj) {
        NSString *token = [responseObj valueForKey:@"token"];
        QNUploadManager *uploadManager = [[QNUploadManager alloc] init];
        QNUploadOption *opt = [[QNUploadOption alloc] initWithProgressHandler:^(NSString *key, float percent) {
            
            _postHud.mode = MBProgressHUDModeDeterminate;
            if (_postHud.progress < percent ) {
                _postHud.progress = percent;
            }
            
        }];
        for (int i = 0; i < self.imagePaths.count; i ++) {
            [uploadManager putFile:self.imagePaths[i] key:nil token:token complete:^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
                if (info.statusCode == 200 && resp) {
                    NSMutableDictionary *page = [NSMutableDictionary dictionary];
                    [page setValue:[NSString stringWithFormat:@"%d",i+1] forKey:@"page"];
                    NSString *realkey = resp[@"key"];
                    [page setValue:realkey forKey:@"pic"];
                    [pages addObject:page];
                    NSData *jsondata = [NSJSONSerialization dataWithJSONObject:pages options:NSJSONWritingPrettyPrinted error:nil];
                    NSString *jsonString = [[NSString alloc] initWithData:jsondata encoding:NSUTF8StringEncoding];
                    NSMutableDictionary *params = [NSMutableDictionary dictionary];
                    [params setValue:self.productInfo.workID forKey:@"works_id"];
                    [params setValue:jsonString forKey:@"pages"];
                    
                    if (pages.count == self.imagePaths.count) {
                        
                        [BPhttpTool post:[NSString stringWithFormat:@"%@works/savepage",BPhttp] params:params success:^(id responseObj) {
                            
                            NSLog(@"--------%@", responseObj);
                            
                            NSDictionary *dic = responseObj;
                            if ([dic[@"status"] intValue] == 1) {
                                
                                _postHud.removeFromSuperViewOnHide = YES;
                                // 1秒之后再消失
                                [_postHud hide:YES];
                                
//                                BPProductShareViewController *shareVc = [[BPProductShareViewController alloc] init];
//                                shareVc.productData = self.productInfo;
//                                shareVc.assetArry = self.alassetArry;
//                                shareVc.leftNav = self.productInfo.category;
//                                shareVc.ImagePath = self.imagePaths;
//                                [self.navigationController pushViewController:shareVc animated:YES];

                                orderDetailVC *orderVc = [[orderDetailVC alloc] init];
                                orderVc.isF = NO;
                                orderVc.webName = @"productDetail.html";
                                orderVc.title = @"作品详情";
                                //传小图路劲
                                orderVc.imagePaths = self.imagePaths;
                                //传产品信息
                                orderVc.productModel = self.productInfo;
                                //传照片数组
                                orderVc.assetArry = self.alassetArry;
                                
                                [self.navigationController pushViewController:orderVc animated:YES];
                                
                                [MBProgressHUD showSuccess:@"上传成功"];
                            }
                        } failure:^(NSError *error) {
                            [MBProgressHUD hideHUD];
                            [MBProgressHUD showError:@"上传失败"];
                        }];
                    }
                }else{
                    [MBProgressHUD hideHUD];
                    [MBProgressHUD showError:@"图片上传失败,请重新上ƒ传"];
                    return;
                }
                
                
            }option:opt];
        }
        
    } failure:^(NSError *error) {
        [MBProgressHUD showError:@"上传图片失败"];
    }];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (NSString *)saveDiyImageToCaches
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyyMMddHHmmss";
    NSString *timeTamp = [formatter stringFromDate:[NSDate date]];
    NSString *ImagePath = [ImageCahes stringByAppendingPathComponent:[NSString stringWithFormat:@"%@add%ld.png",timeTamp,(long)_pageNumber]];
    [UIImageJPEGRepresentation([_userEnableView setUpANewImage:_DIYimageSize], 0.9)writeToFile:ImagePath atomically:YES];
    //[UIImagePNGRepresentation([_userEnableView setUpANewImage:_DIYimageSize])writeToFile:ImagePath atomically:YES];
    return ImagePath;
}

- (void)removeArryObject{
    if (![[self.diyImageTotal objectAtIndex:_pageNumber] isEqualToString:@""]) {
        [self.diyImageTotal replaceObjectAtIndex:_pageNumber withObject:@""];
        _clickNO = _clickNO - 1;
    }
}

//返回按钮
- (void)navTap:(UITapGestureRecognizer *)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}
//数据初始化
- (void)setUpUIData
{
//    [BPhttpTool get:[NSString stringWithFormat:@"%@Appapi/getmaterial/type/4",BPhttp] params:nil success:^(id responseObj) {
//        
//        _textColors = responseObj;       
//    } failure:^(NSError *error) {
//        
//    }];
    
    MyproductManger = [[CoreDateManager alloc] init];
    _diyImageTotal = [NSMutableArray array];
    _clickNO = self.productInfo.pages.count;
    _imagePaths = [NSMutableArray array];
    _DIYimageSize = CGSizeMake(self.productInfo.page_w, self.productInfo.page_h);
    _isPost = NO;
    
    // 字体
    _serviceFont = [NSArray arrayWithObjects:@"FZZDXJW--GB1-0",@"fangzhenjianti",@"fzqkbysjianti",@"fzxxlfw",@"xjlfont", nil];
    _textColors = [NSArray arrayWithObjects:@"#FFFFFF",@"#000000",@" ",@"#E2F1EA",@"#D8E7EF", nil];
    
    [self DownloadShadingAndBackcolor];
    
    for (int i = 0; i < self.productInfo.pages.count; i++) {
        [_diyImageTotal addObject:[NSString stringWithFormat:@"第%d页",i + 1]];
        BPProductDetailPage *topImage = self.productInfo.pages[i];
        [_imagePaths addObject:topImage.base_img];
    }
    //第一次进来据需要给model里面的index和assetStr赋值
    if (_isFirst == YES) {
        //制作的时候进来
        int index = 0;
        int jdx = 100;
        for (BPProductDetailPage *pages in self.productInfo.pages) {
            for (BPProductModel *models in pages.moulds) {
                if (models.type == 0) {
                    //给照片mould设置编号，同时传给他照片地址
                    models.modelIndex = index;
                    ALAsset *asset = self.alassetArry[index];
                    models.alassetStr = [[asset defaultRepresentation].url absoluteString];
                    index++;
                }else if (models.type == 1){
                    models.modelIndex = jdx;
                    jdx++;
                }
            }
        }
    }
}

#pragma 添加view
- (void)drawUIView
{
    self.view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.centerView];
    [self.view addSubview:self.mubanView];
    [self.view addSubview:self.backShading];
    [self.view addSubview:self.backViewColor];
    [self.view addSubview:self.keyboardView];
    [self.view addSubview:self.imageChangeView];
    
}

#pragma - mark 中间视图包括海报大小、自定义区域等
- (UIView *)centerView
{
    if (!_centerView) {
        _centerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, BPScreenW, BPScreenH)];
        
        //1.添加一块用户操作区域
        [self setUpCustomView];
        
        //2.设置滤镜和工具条
        [self setUpAssetBottomFilterAndToolbar];
        
        //3.设置基本按钮
        [self setUpCenterViewButton];
    }
    return _centerView;
}

#pragma - mark 设置ui界面
#pragma - mark 添加DIY操作区域userEnableView
- (void)setUpCustomView
{
    _pageNumber = 0;
    
    //设置灰色区域位置
    CGFloat backH = BPScreenH - buttomH - BPStatusCellInset * 2.0 - BPScreenNavY - buttomToolH;
    _garyBgView = [[UIView alloc] initWithFrame:CGRectMake(BPStatusCellInset, BPStatusCellInset + BPScreenNavY, BPScreenW - 2 * BPStatusCellInset, backH)];
    [_garyBgView.layer setBorderColor:[BPHuiColor CGColor]];
    _garyBgView.backgroundColor = BPHuiColor;
    [_garyBgView.layer setBorderWidth:4.0f];
    UITapGestureRecognizer *hide = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hidebackView)];
    [_garyBgView addGestureRecognizer:hide];
    [_centerView addSubview:_garyBgView];
    
    [self setUpUserEnableView];
    [_userEnableView setUpUserEnableView:self.productInfo.pages[_pageNumber] withScale:self.productInfo.scale addAssetarry:self.alassetArry addimageScale:self.productInfo.bigScale addDiySize:_userEnableView.size];
    self.title = @"第1页";
    self.pageInfo = self.productInfo.pages[_pageNumber];
    [self setUpCustomViewAndTextDelegate];
    
    
}

//设置台历操作区域
- (void)setUpUserEnableView
{
    if (self.productInfo.edit_w == 0) {
        self.productInfo.edit_w = 500.0;
    }
    CGFloat changkuanScale = (self.productInfo.page_h / self.productInfo.page_w);
    CGFloat editH = changkuanScale *self.productInfo.edit_w;
    CGFloat editW = self.productInfo.edit_w;
    CGFloat bigScale = self.productInfo.edit_w / self.productInfo.page_w;
    
    if ((_garyBgView.width / editW) > (_garyBgView.height / editH)) {
        CGFloat scale = (_garyBgView.height - 10.0) / editH;
        CGFloat viewW = editW *scale;
        _userEnableView = [[BPHeartMakeCenterView alloc] initWithFrame:CGRectMake((_garyBgView.width - viewW)/2.0, 5.0, viewW, _garyBgView.height - 10.0)];
        self.productInfo.scale = scale;
        self.productInfo.bigScale = scale * bigScale;
    }else{
        CGFloat scale = (_garyBgView.width - 10.0) / editW;
        CGFloat viewH = editH *scale;
        _userEnableView = [[BPHeartMakeCenterView alloc] initWithFrame:CGRectMake(5.0, (_garyBgView.height - viewH)/2.0, _garyBgView.width - 10.0, viewH)];
         self.productInfo.scale = scale;
        self.productInfo.bigScale = scale * bigScale;
    }
    [self fadeViewIn:_userEnableView];
    [_garyBgView addSubview:_userEnableView];
}

#pragma - mark 添加照片下面的滤镜和工具条
- (void)setUpAssetBottomFilterAndToolbar
{
    //照片工具条
    CGFloat ToolbtnD = 5.0f;
    CGFloat ToolbtnW = (BPScreenW / 2.0 - 4.0 * ToolbtnD)/5.0;
    CGFloat toolBarH = ToolbtnW;
    CGFloat toolBarW = BPScreenW / 2.0;
    _customToolBar = [[customViewToolBar alloc] initWithFrame:CGRectMake(0, 0, toolBarW, toolBarH)];
    _customToolBar.delegate = self;
}


#pragma - mark 添加centerView上面的按钮，两侧和底部的按钮
- (void)setUpCenterViewButton
{
    UIView *buttomView = [[UIView alloc] initWithFrame:CGRectMake(0, BPScreenH - buttomH, BPScreenW, buttomH)];
    buttomView.backgroundColor = [UIColor blackColor];
    [_centerView addSubview:buttomView];
    
    
    
    //设置底部四个按钮
    HMSegmentedControl *textStyleBtn = [[HMSegmentedControl alloc] initWithSectionTitles:@[@"模板",@"背景",@"底纹",@"字体"]];

    textStyleBtn.textColor = [UIColor whiteColor];
    [textStyleBtn setFrame:buttomView.bounds];
    
    
    CGFloat imageX = 40.0f;
    CGFloat imageY = 2.0f;
    CGFloat imageW = 20.0f;
    CGFloat imageH = 20.0f;
    
    // 模板
    UIView *a = [[UIView alloc] initWithFrame:CGRectMake(0, 0, textStyleBtn.frame.size.width / 3, 40)];
    a.backgroundColor = [UIColor blackColor];
    a.tag = 1;
    [textStyleBtn addSubview:a];
    
    self.ima = [[UIImageView alloc] initWithFrame:CGRectMake(imageX, imageY, imageW, imageH)];
    self.ima.image = [UIImage imageNamed:@"moBan"];
    [a addSubview:self.ima];
    
    self.labA = [[UILabel alloc] initWithFrame:CGRectMake(imageX - 25, imageX - 19, imageX + 30, imageX - 20)];
    self.labA.text = @"模板";
    self.labA.textAlignment = 1;
    self.labA.font = [UIFont systemFontOfSize:13];
    self.labA.textColor = [UIColor whiteColor];
    [a addSubview:self.labA];
    
    UITapGestureRecognizer *tapA = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapA:)];
    [a addGestureRecognizer:tapA];
    
    
    // 底纹
    UIView *b = [[UIView alloc] initWithFrame:CGRectMake(textStyleBtn.frame.size.width / 3, 0, textStyleBtn.frame.size.width / 3, 40)];
    b.backgroundColor = [UIColor blackColor];
    b.tag = 2;
    [textStyleBtn addSubview:b];
    
    self.imb = [[UIImageView alloc] initWithFrame:CGRectMake(imageX, imageY, imageW, imageH)];
    self.imb.image = [UIImage imageNamed:@"diwen"];
    [b addSubview:self.imb];
    UITapGestureRecognizer *tapB = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapA:)];
    [b addGestureRecognizer:tapB];
    
    self.labB = [[UILabel alloc] initWithFrame:CGRectMake(imageX - 25, imageX - 19, imageX + 30, imageX - 20)];
    self.labB.text = @"背景";
    self.labB.textAlignment = 1;
    self.labB.font = [UIFont systemFontOfSize:13];
    self.labB.textColor = [UIColor whiteColor];
    [b addSubview:self.labB];
    
    
    // 背景
    UIView *c = [[UIView alloc] initWithFrame:CGRectMake(textStyleBtn.frame.size.width / 3 + textStyleBtn.frame.size.width / 3, 0, textStyleBtn.frame.size.width / 3, 40)];
    c.backgroundColor = [UIColor blackColor];
    c.tag = 3;
    [textStyleBtn addSubview:c];
    
    self.imc = [[UIImageView alloc] initWithFrame:CGRectMake(imageX, imageY, imageW, imageH)];
    self.imc.image = [UIImage imageNamed:@"beijing"];
    [c addSubview:self.imc];
    UITapGestureRecognizer *tapC = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapA:)];
    [c addGestureRecognizer:tapC];
    
    self.labC = [[UILabel alloc] initWithFrame:CGRectMake(imageX - 25, imageX - 19, imageX + 30, imageX - 20)];
    self.labC.text = @"底纹";
    self.labC.textAlignment = 1;
    self.labC.font = [UIFont systemFontOfSize:13];
    self.labC.textColor = [UIColor whiteColor];
    [c addSubview:self.labC];
    
    
    
//    // 字体
//    UIView *d = [[UIView alloc] initWithFrame:CGRectMake(textStyleBtn.frame.size.width / 4 + textStyleBtn.frame.size.width / 4 + textStyleBtn.frame.size.width / 4, 0, textStyleBtn.frame.size.width / 4, 40)];
//    d.backgroundColor = [UIColor blackColor];
//    d.tag = 4;
//    [textStyleBtn addSubview:d];
//    
//    self.imd = [[UIImageView alloc] initWithFrame:CGRectMake(imageX, imageY, imageW, imageH)];
//    self.imd.image = [UIImage imageNamed:@"diwen"];
//    [d addSubview:self.imd];
//    UITapGestureRecognizer *tapD = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapA:)];
//    [d addGestureRecognizer:tapD];
//    
//    self.labD = [[UILabel alloc] initWithFrame:CGRectMake(imageX - 20, imageX - 5, imageX + 30, imageX - 20)];
//    self.labD.text = @"字体";
//    self.labD.textAlignment = 1;
//    self.labD.font = [UIFont systemFontOfSize:13];
//    self.labD.textColor = [UIColor whiteColor];
//    [d addSubview:self.labD];
    
    
    
//    [textStyleBtn setIndexChangeBlock:^(NSUInteger index) {
//        switch (index) {
//            case 0:
//                //显示模板，隐藏底纹、背景
//                                
//                [self buttomTableViewDisappear];
//                [self buttomTableViewappear:_mubanView setY:buttomToolH + buttomH];
//                break;
//            case 1:
//                //显示底纹、隐藏背景和模板
//                [self buttomTableViewDisappear];
//                [self buttomTableViewappear:_backShading setY:buttomToolH + buttomH];
//                break;
//                
//            case 2:
//                //显示背景、隐藏底纹和模板
//                [self buttomTableViewDisappear];
//                [self buttomTableViewappear:_backViewColor setY:buttomToolH + buttomH];
//                break;
//                
//            case 3:
//                //显示键盘
//                _isKeyboard = NO;
//                [self keyBoardShow];
//                break;
//                
//            default:
//
//                break;
//        }
//    }];
    [buttomView addSubview:textStyleBtn];

}


- (void)tapA:(UITapGestureRecognizer *)tap{
    switch (tap.view.tag) {
        case 1:
            //显示模板，隐藏底纹、背景
            
            self.labB.textColor = [UIColor whiteColor];
            self.labC.textColor = [UIColor whiteColor];
            self.labD.textColor = [UIColor whiteColor];
            self.labA.textColor = BPFenHongColor;
            
            self.imb.image = [UIImage imageNamed:@"diwen"];
            self.imc.image = [UIImage imageNamed:@"beijing"];
            self.imd.image = [UIImage imageNamed:@"moBan"];
            self.ima.image = [UIImage imageNamed:@"moban-over"];
            
            [self buttomTableViewDisappear];
            [self buttomTableViewappear:_mubanView setY:buttomToolH + buttomH];
            break;
        case 3:
            
            //显示底纹、隐藏背景和模板
            self.labA.textColor = [UIColor whiteColor];
            self.labC.textColor = BPFenHongColor;
            self.labD.textColor = [UIColor whiteColor];
            self.labB.textColor = [UIColor whiteColor];
            
            self.ima.image = [UIImage imageNamed:@"moBan"];
            self.imc.image = [UIImage imageNamed:@"beijing-over"];
            self.imd.image = [UIImage imageNamed:@"moBan"];
            self.imb.image = [UIImage imageNamed:@"diwen"];
            [self buttomTableViewDisappear];
            [self buttomTableViewappear:_backShading setY:buttomToolH + buttomH];
            break;
            
        case 2:
            //显示背景、隐藏底纹和模板
            self.labA.textColor = [UIColor whiteColor];
            self.labB.textColor = BPFenHongColor;
            self.labD.textColor = [UIColor whiteColor];
            self.labC.textColor = [UIColor whiteColor];
            
            self.ima.image = [UIImage imageNamed:@"moBan"];
            self.imb.image = [UIImage imageNamed:@"diwen-over"];
            self.imd.image = [UIImage imageNamed:@"moBan"];
            self.imc.image = [UIImage imageNamed:@"beijing"];
            [self buttomTableViewDisappear];
            [self buttomTableViewappear:_backViewColor setY:buttomToolH + buttomH];
            break;
            
        case 4:
            
            self.labA.textColor = [UIColor whiteColor];
            self.labB.textColor = [UIColor whiteColor];
            self.labC.textColor = [UIColor whiteColor];
            self.labD.textColor = BPFenHongColor;

            
            self.ima.image = [UIImage imageNamed:@"moBan"];
            self.imb.image = [UIImage imageNamed:@"diwen"];
            self.imc.image = [UIImage imageNamed:@"beijing"];
            self.imd.image = [UIImage imageNamed:@"moban-over"];
            [self buttomTableViewDisappear];
            //显示键盘
            _isKeyboard = NO;
            [self keyBoardShow];
            break;
            
        default:
            
            break;
    }
    
}



#pragma - mark swipe代理设置
- (NSInteger)numberOfItemsInSwipeView:(SwipeView *)swipeView
{
    if (swipeView == _topScanScrollView) {
        return self.imagePaths.count;
    }else if (swipeView == _shadingScrollview){
        return [_shadingArry count];
    }else if (swipeView == _imageScrollview){
        return 5;
    }
    else{
        return [_colorArry count];
    }
}

//更改底部是图的关键
- (UIView *)swipeView:(SwipeView *)swipeView viewForItemAtIndex:(NSInteger)index reusingView:(UIView *)view
{
    
    CGFloat imageViewGap = 10.0f;
    CGFloat imageViewW = 70.0f;
    
    if (swipeView == _topScanScrollView) {
        UIImageView *templateImage = nil;
        if (view == nil) {
            view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, imageViewGap + imageViewW, _topScanScrollView.height)];
            templateImage = [[UIImageView alloc] initWithFrame:CGRectMake(imageViewGap / 2.0, imageViewGap / 2.0, view.width - imageViewGap, view.height - imageViewGap)];
            templateImage.tag = 1;
            // 模板的 边框 颜色
          //  [templateImage.layer setBorderColor:[BPGlobaBGColor CGColor]];
            //[templateImage.layer setBorderWidth:0.7];
            templateImage.contentMode = UIViewContentModeScaleAspectFit;
            [view addSubview:templateImage];

            // 设置 图片上的 label
            _label = [[UILabel alloc] initWithFrame:CGRectMake(0, 42, view.width - imageViewGap, 18)];
            if (index == self.cviewIndex){
                _label.backgroundColor = BPGlobaThemeColor;
                _label.textColor = [UIColor blackColor];
            }
            else{
                _label.backgroundColor = [UIColor blackColor];
                _label.textColor = BPFenHongColor;
            }
            _label.alpha = 0.7;
            _label.textAlignment = 1;
            _label.font = [UIFont systemFontOfSize:13.0f];
            [templateImage addSubview:_label];
        }else{
            templateImage = (UIImageView *)[view viewWithTag:1];
        }
        
        // 设置 label 上要显示的 文字
        UILabel *cLabel=(UILabel *)templateImage.subviews[0];
        if (index==self.cviewIndex){
            cLabel.backgroundColor = BPGlobaThemeColor;
            cLabel.textColor = [UIColor blackColor];
        }
        else{
            cLabel.backgroundColor = [UIColor blackColor];
            cLabel.textColor = BPFenHongColor;
        }
        cLabel.text = [NSString stringWithFormat: @"P%ld", (long)index+1];
        [BPImageTool setTopImage:templateImage addUrl:_imagePaths[index]];

        return view;
        
    }else if(swipeView == _shadingScrollview){
        UIImageView *templateImage = nil;
        
        if (view == nil) {
            view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, _backShading.height, _backShading.height)];
            templateImage = [[UIImageView alloc] initWithFrame:CGRectMake(4, 4, view.width - 8.0, view.height - 8.0)];
            
            // 底纹的 颜色
            templateImage.backgroundColor = [UIColor grayColor];
//            [templateImage.layer setCornerRadius:5.0];
//            [templateImage.layer setBorderWidth:2.0f];
            // 底纹的每个框框 的 边框 颜色
            [templateImage.layer setBorderColor:[BPGlobaBGColor CGColor]];
            templateImage.tag = 1;
            [view addSubview:templateImage];
            
            _labelDiWen = [[UILabel alloc] initWithFrame:CGRectMake(0, 44, view.width - 8.0, 18)];
            if (index == self.diWenIndex){
                _labelDiWen.backgroundColor = BPGlobaThemeColor;
                _labelDiWen.textColor = [UIColor blackColor];
            }
            else{
                _labelDiWen.backgroundColor = [UIColor blackColor];
                _labelDiWen.textColor = BPFenHongColor;
            }
            
            _labelDiWen.alpha = 0.7;
            _labelDiWen.textAlignment = 1;
            _labelDiWen.font = [UIFont systemFontOfSize:13.0f];
            [templateImage addSubview:_labelDiWen];

        }else{
            templateImage = (UIImageView *)[view viewWithTag:1];
        }
        
        // 设置 label 上要显示的 文字
        UILabel *cLabel=(UILabel *)templateImage.subviews[0];
        if (index == self.diWenIndex){
            cLabel.backgroundColor = BPGlobaThemeColor;
            cLabel.textColor = [UIColor blackColor];
        }
        else{
            cLabel.backgroundColor = [UIColor blackColor];
            cLabel.textColor = BPFenHongColor;
        }
        
        cLabel.text = [NSString stringWithFormat: @"No.%ld", (long)index+1];
        [BPImageTool shadingThumb:templateImage withUrl:_shadingArry[index]];
        return view;
        
    }else{
        // 背景的 边框颜色
        UIImageView *templateImage = nil;
        if (view == nil) {
            view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, _backShading.height, _backShading.height)];
            
            templateImage = [[UIImageView alloc] initWithFrame:CGRectMake(4, 4, view.width - 8.0, view.height - 8.0)];
            [templateImage setBackgroundColor:[UIColor colorWithHexString:_colorArry[index]]];
//            [templateImage.layer setCornerRadius:5.0];
//            [templateImage.layer setBorderWidth:2.0f];
            [templateImage.layer setBorderColor:[BPGlobaBGColor CGColor]];
            templateImage.tag = 1;
            
            [view addSubview:templateImage];
            
            _BeijingLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 44, view.width - 8.0, 18)];
            if (index == self.beijingIndex){
                _BeijingLabel.backgroundColor = BPGlobaThemeColor;
                _BeijingLabel.textColor = [UIColor blackColor];
            }
            else{
                _BeijingLabel.backgroundColor = [UIColor blackColor];
                _BeijingLabel.textColor = BPFenHongColor;
            }
            
            _BeijingLabel.alpha = 0.7;
            _BeijingLabel.textAlignment = 1;
            _BeijingLabel.font = [UIFont systemFontOfSize:13.0f];
            [templateImage addSubview:_BeijingLabel];
        }else{
            templateImage = (UIImageView *)[view viewWithTag:1];
        }
        // 设置 label 上要显示的 文字
        UILabel *cLabel=(UILabel *)templateImage.subviews[0];
        if (index == self.beijingIndex){
            cLabel.backgroundColor = BPGlobaThemeColor;
            cLabel.textColor = [UIColor blackColor];
        }
        else{
            cLabel.backgroundColor = [UIColor blackColor];
            cLabel.textColor = BPFenHongColor;
        }
        
        cLabel.text = [NSString stringWithFormat: @"No.%ld", (long)index+1];
        //[BPImageTool shadingThumb:templateImage withUrl:_shadingArry[index]];
        return view;
    }
}


#pragma - mark添加点击事件
#pragma swipe的点击事件
- (void)swipeView:(SwipeView *)swipeView didSelectItemAtIndex:(NSInteger)index
{
    
    if (swipeView == _topScanScrollView) {
        
        self.cviewIndex = index;

        //[self hidebackView];
        CGRect curFrame = [_topScanScrollView itemViewAtIndex:index].frame;
        
        //生成一张图片,保存在本地
        [_imagePaths replaceObjectAtIndex:_pageNumber withObject:[self saveDiyImageToCaches]];
        
        [_topScanScrollView reloadData];
        
        //取出那张点过的照片，不需要再生成,同时只进来一次
        [self removeArryObject];
        
        //1.保存上个界面的信息
        [_userEnableView savePageInfo:self.productInfo.pages[_pageNumber]];
        
        //2.去除上个页面的ui
        [_userEnableView resetAssetView];
        
        self.label.backgroundColor = BPGlobaThemeColor;
        if (index > _pageNumber) {
            [self rightAnimation];
        }else if(index < _pageNumber){
            [self leftAnimation];
        }else{
            [self fadeViewIn:_userEnableView];
        }
        
        //3.给pagenumber赋值
        _pageNumber = index;

        // 粉色的框框
        _topCurView.frame = curFrame;
//        _topCurView.x = _topCurView.x + 3.0;
//        _topCurView.y = _topCurView.y + 3.0;
//        _topCurView.width = _topCurView.width - 6.0;
//        _topCurView.height = _topCurView.height - 6.0;
        
        // 粉色的 条条
        _topCurView.x = _topCurView.x + 3.0;
        _topCurView.y = _topCurView.y + 45.0;
        _topCurView.width = _topCurView.width - 6.0;
        _topCurView.height = _topCurView.height / 3;
        
        
        
        //4.传递当前页面信息
        [_userEnableView setUpUserEnableView:self.productInfo.pages[_pageNumber] withScale:self.productInfo.scale addAssetarry:self.alassetArry addimageScale:self.productInfo.bigScale addDiySize:_userEnableView.size];
        
        self.pageInfo = self.productInfo.pages[_pageNumber];
        self.labelName.text = [NSString stringWithFormat:@"第%ld页",index+1];
        
        _currentView.size = CGSizeZero;
        //_topCurView.size = CGSizeZero;
        _btnView.size = CGSizeZero;
        //5.设置文字和图片区域的代理
        [self setUpCustomViewAndTextDelegate];
        
    }else if(swipeView == _shadingScrollview){
        self.diWenIndex = index;
        
        CGRect curFrame = [_shadingScrollview itemViewAtIndex:index].frame;
        _currentView.frame = curFrame;
        //更换底纹
        [self changeDiyBackShadingImage:index];
        [_shadingScrollview reloadData];
    }else {
        self.beijingIndex = index;
        _userEnableView.backgroundColor = [UIColor colorWithHexString:_colorArry[index]];
        self.pageInfo.bg_color = _colorArry[index];
        [_bgColorScrollview reloadData];
    }
}

- (void)setUpCustomViewAndTextDelegate
{
    for (id subobject in _userEnableView.assetView.subviews) {
        if ([subobject isKindOfClass:[BPCustomView class]]) {
            _senderImage = (BPCustomView *)subobject;
            _senderImage.delegate = self;
        }
    }
    for (id subobj in _userEnableView.subviews) {
        if ([subobj isKindOfClass:[BPCustomLabel class]]) {
            _senderText = (BPCustomLabel *)subobj;
            _senderText.delegate = self;
        }
    }
}

// 点击文字 弹出 键盘框框
- (void)tapCustomLabel:(UITapGestureRecognizer *)sender
{
    _senderText = (BPCustomLabel *)sender.view;
    [self buttomTableViewDisappear];
    [self buttomTableViewappear:_mubanView setY:buttomToolH + buttomH];
    [self keyBoardShow];
}

#pragma - mark 添加BPcustom的代理,长按显示工具条和点击出现滤镜，拖动、平移和旋转
- (void)backViewTapOne:(UITapGestureRecognizer *)sender
{
    _senderImage = (BPCustomView *)sender.view;
    [self albumChoose];
}

//长按
- (void)backViewPressLong:(UILongPressGestureRecognizer *)sender
{
    _senderImage = (BPCustomView *)sender.view;
    [self hidebackView];
    //处理frame
//    CGRect overHandelFrame = [self transformSenderFrame:_senderImage];
//    
//    NSValue *frameValue = [NSValue valueWithCGRect:overHandelFrame];
//    
//    _customToolBar.x = overHandelFrame.origin.x + (_senderImage.width - _customToolBar.width) / 2.0;
//    _customToolBar.y = CGRectGetMaxY(overHandelFrame);
//    
//    if (_senderImage.height + _senderImage.y + _customToolBar.height > _garyBgView.height) {
//        _customToolBar.y = CGRectGetMaxY(overHandelFrame) - _customToolBar.height;
//    }
//    
//    [self presentPopupView:_customToolBar animationType:MJPopupViewAnimationFade addView:frameValue];
    
//    _customToolBar.x = 10;
//    _customToolBar.y = 10;
//    _customToolBar.width = 100;
//    _customToolBar.height = 30;
    
    // 底部的 试图的 显示 和 消失
    [self zidingyiJIanpanDisappear];
    [self buttomTableViewDisappear];
    [self buttomTableViewappear:_imageChangeView setY:buttomToolH + buttomH];
}
#pragma - mark 计算文字模块和图片模块在整个屏幕的坐标位置
- (CGRect)transformSenderFrame:(BPCustomView *)senderFrameInUsrView
{
    CGFloat viewY = senderFrameInUsrView.y + _userEnableView.y + _garyBgView.y;
    CGFloat viewX = senderFrameInUsrView.x + _userEnableView.x + _garyBgView.x;
    CGRect handle = (CGRect){{viewX,viewY},senderFrameInUsrView.size};
    
    return handle;
}

- (CGRect)showFullScreen:(BPCustomLabel *)senderLabel
{
    CGFloat viewY = senderLabel.y + _userEnableView.y + _garyBgView.y;
    CGFloat viewX = senderLabel.x + _userEnableView.x + _garyBgView.x;
    CGRect handle = (CGRect){{viewX,viewY},senderLabel.size};
    
    return handle;
}

//旋转
- (void)rotaImage
{
    _senderImage.assetImage.transform=CGAffineTransformRotate(_senderImage.assetImage.transform, M_PI_2);
}

#pragma - mark 工具条点击事件代理
//换照片
- (void)albumChoose
{
    [D_Main_Appdelegate preview].isAddPic = NO;
    if (_picturePicker == nil) {
        _picturePicker = [[ZYQAssetPickerController alloc] init];
        _picturePicker.delegate = self;
        _picturePicker.assetsFilter = [ALAssetsFilter allPhotos];
        _picturePicker.showEmptyGroups = NO;
    }
    _picturePicker.selectionFilter = [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {
        if ([[(ALAsset*)evaluatedObject valueForProperty:ALAssetPropertyType] isEqual:ALAssetTypeVideo]) {
            NSTimeInterval duration = [[(ALAsset*)evaluatedObject valueForProperty:ALAssetPropertyDuration] doubleValue];
            return duration >= 5;
        } else {
            return YES;
        }
    }];
    _picturePicker.vc = self;
    [self presentViewController:_picturePicker animated:YES completion:nil];
}

- (void)assetPickerController:(ZYQAssetPickerController *)picker didSelectAsset:(ALAsset *)asset
{
    [MBProgressHUD showMessage:@"正在处理"];
    UIImage *image = [[UIImage alloc] init];
    //更换照片选择条里的照片
//    if ([D_Main_Appdelegate preview].imageassets != nil) {
//        [[D_Main_Appdelegate preview].imageassets replaceObjectAtIndex:_senderImage.tag withObject:asset];
//        CGImageRef ref = [asset thumbnail];
//        image = [UIImage imageWithCGImage:ref];
//        ImageEditView *editimage = [D_Main_Appdelegate preview].imageEditViewArray[_senderImage.tag];
//        editimage.imageView.image = image;
//    }
    
    if (_isFirst == YES) {
        [[D_Main_Appdelegate preview].imageassets replaceObjectAtIndex:_senderImage.tag withObject:asset];
        CGImageRef ref = [asset thumbnail];
        image = [UIImage imageWithCGImage:ref];
        ImageEditView *editimage = [D_Main_Appdelegate preview].imageEditViewArray[_senderImage.tag];
        editimage.imageView.image = image;
    }
    
    [_alassetArry replaceObjectAtIndex:_senderImage.tag withObject:asset];
    //当前选择照片显示出来
    CGImageRef ref2 = [[asset defaultRepresentation] fullScreenImage];
    image = [UIImage imageWithCGImage:ref2];
    [_senderImage.assetImage setTransform:CGAffineTransformIdentity];
    _senderImage.assetImage.image = image;
    CGSize assetSize = [asset defaultRepresentation].dimensions;
    _senderImage.assetWith = assetSize.width;
    if (_senderImage.noPicImage != nil) {
        [_senderImage removenoPicimage];
    }
    
    if (assetSize.width * self.productInfo.bigScale < _senderImage.assetImage.width) {
        if (_senderImage.nopxImage == nil && _senderImage.imageVBlock == nil) {
            [_senderImage setUpnopxImageView];
        }
    }else{
        if (_senderImage.nopxImage != nil && _senderImage.imageVBlock != nil) {
            [_senderImage removePXimage];
        }
    }
    
    //存数据
    self.pageInfo = self.productInfo.pages[_pageNumber];
    for (BPProductModel *model in self.pageInfo.moulds) {
        if (model.modelIndex == _senderImage.tag) {
            model.alassetStr = [[asset defaultRepresentation].url absoluteString];
        }
    }
    image = nil;
    [self performSelector:@selector(backDiy) withObject:nil afterDelay:0.5];
}

- (void)backDiy
{
    [D_Main_Appdelegate preview].isAddPic = YES;
    [_picturePicker dismissViewControllerAnimated:YES completion:nil];
    [MBProgressHUD hideHUD];
}

//镜像
- (void)mirrorImage
{
    //_senderImage.assetImage.transform = CGAffineTransformScale(_senderImage.transform, -1.0, 1.0);
    _senderImage.assetImage.a = -_senderImage.assetImage.a;
    _senderImage.assetImage.c = -_senderImage.assetImage.c;
}

//放大
- (void)addImageSize
{
    CGAffineTransform currentTransform = _senderImage.assetImage.transform;
    CGAffineTransform newTransform = CGAffineTransformScale(currentTransform, 1.1, 1.1);
    [_senderImage.assetImage setTransform:newTransform];
    
    if (_senderImage.assetWith * self.productInfo.bigScale < _senderImage.assetImage.width) {
        if (_senderImage.nopxImage == nil && _senderImage.imageVBlock == nil) {
            [_senderImage setUpnopxImageView];
        }
    }
}

//缩小
- (void)reduceImageSize
{
    CGAffineTransform currentTransform = _senderImage.assetImage.transform;
    CGAffineTransform newTransform = CGAffineTransformScale(currentTransform, 0.9, 0.9);
    [_senderImage.assetImage setTransform:newTransform];
    
    if (_senderImage.assetWith * self.productInfo.bigScale > _senderImage.assetImage.width) {
        if (_senderImage.nopxImage != nil && _senderImage.imageVBlock != nil) {
            [_senderImage removePXimage];
        }
    }
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    if (_senderText != nil) {
        [self panduanTextDirection];
    }
    
    
    
    
    for (BPProductModel *model in self.pageInfo.moulds) {
        if (model.modelIndex == _senderText.tag) {
            model.text = _senderText.text;
        }
    }
}

-(void)panduanTextDirection
{
    if (_senderText.textDirection == 0) {
        //水平
        [_senderText horizontalSetUpText:_toolBar.importText.text];
    }else{
        //垂直
        [_senderText verticalSetUpText:_toolBar.importText.text];
    }
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    //隐藏键盘和自定义键盘
    [self zidingyiJIanpanDisappear];
    return YES;
}

#pragma mark - 设置底部自定义键盘视图
#pragma mark - 设置键盘view
- (UIView *)keyboardView
{
    if (!_keyboardView) {
        CGFloat textToolBarH = 50;
        CGFloat tableViewH = 210.0;
        _keyboardView = [[UIView alloc] initWithFrame:CGRectMake(0, BPScreenH, BPScreenW, tableViewH + textToolBarH)];
        
        keyboardView *keyboard = [[keyboardView alloc] initWithFrame:CGRectMake(0, textToolBarH, BPScreenW, tableViewH)];
        keyboard.delegate = self;
        [_keyboardView addSubview:keyboard];
        _toolBar = [[keyboardToolBar alloc] initWithFrame:CGRectMake(0, 0, BPScreenW, textToolBarH)];
        _toolBar.delegate = self;
        _toolBar.importText.delegate = self;
        [_keyboardView addSubview:_toolBar];
    }
    return _keyboardView;
}


- (void)didClickCell:(keyboardModel *)keyboardCell with:(int)indexRow
{
    if ([keyboardCell.textType isEqualToString:@"字体"]) {
        
        _senderText.font = [UIFont fontWithName:keyboardCell.textFont size:_senderText.textfontSize];
        for (BPProductModel *model in self.pageInfo.moulds) {
            if (model.modelIndex == _senderText.tag) {
                model.font = _serviceFont[indexRow];
            }
        }
        
    }else if ([keyboardCell.textType isEqualToString:@"颜色"]){
        
        _senderText.textColor = [UIColor colorWithHexString:keyboardCell.textColor];
        for (BPProductModel *model in self.pageInfo.moulds) {
            if (model.modelIndex == _senderText.tag) {
                model.color = keyboardCell.textColor;
            }
        }
        
    }
    else{
        
        _senderText.font = [UIFont fontWithName:_senderText.sbfont size:keyboardCell.textSize - 4.0f];
        _senderText.textfontSize = keyboardCell.textSize;

        for (BPProductModel *model in self.pageInfo.moulds) {
            if (model.modelIndex == _senderText.tag) {
                model.size = keyboardCell.textSize / self.productInfo.scale;
            }
        }
    }
}

#pragma - mark 工具条的点击事件代理
- (void)keyboardTool:(keyboardToolBar *)toolbar didClickedButton:(BPkeyboardToolBarButtonType)buttonType
{
    switch (buttonType) {
        case BPkeyboardToolBarButtonTypeText:
            [self openKeyboard];
            break;
            
        case BPkeyboardToolBarButtonTypeSend:
            //隐藏键盘和自定义键盘
            [self zidingyiJIanpanDisappear];
            
            break;
            
        default:
            break;
    }
}

#pragma mark - 工具条上点击事件-打开键盘
- (void)openKeyboard
{
    //假如键盘是打开的，点击则停止编辑，显示tablview，图标换成键盘
    if (_isKeyboard == YES) {
        [self.view endEditing:YES];
    }else
        //假如键盘是关闭的，点击则开始编辑，启动键盘，图标换成T。
    {
        [_toolBar.importText becomeFirstResponder];
    }
}

#pragma mark - 设置键盘工具条的位置和动画
- (void)keyboardWillShow:(NSNotification *)note
{
    CGFloat duration = [note.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    //[self buttomTableViewappear:self.keyboardView setY:BPScreenH - self.keyboardView.height];
    //当键盘取出时，图标显示为T。
    [_toolBar setShowTextStyle:YES];
    _isKeyboard = YES;
    // 2.动画
    [UIView animateWithDuration:duration animations:^{
        
        // 取出键盘高度
        CGRect keyboardF = [note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
        
        CGFloat keyboardH = keyboardF.size.height;
        
        _keyboardView.y = BPScreenH - keyboardH - _toolBar.height;
        //NSLog(@"%f",_keyboardView.y);
    }];
}

- (void)keyboardWillHide:(NSNotification *)note
{
    //图标显示为键盘
    [_toolBar setShowTextStyle:NO];
    _isKeyboard = NO;
    // 1.键盘弹出需要的时间
    CGFloat duration = [note.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    // 2.动画
    [UIView animateWithDuration:duration animations:^{
        
        _keyboardView.y = BPScreenH - 260;
    }];
}

#pragma - mark 添加模板滚动条
- (UIView *)mubanView
{
    if (_mubanView == nil) {
        _mubanView = [[UIView alloc] initWithFrame:CGRectMake(0, BPScreenH, BPScreenW, buttomToolH)];
        _mubanView.backgroundColor = [UIColor blackColor];
        
        _topScanScrollView = [[SwipeView alloc] initWithFrame:_mubanView.bounds];
        _topScanScrollView.delegate = self;
        _topScanScrollView.dataSource = self;
        [_mubanView addSubview:_topScanScrollView];
        
        //// 模板的 选中框
        _topCurView = [[UIView alloc] init];
//        [_topCurView.layer setBorderColor:[BPGlobaThemeColor CGColor]];
        _topCurView.backgroundColor = BPGlobaThemeColor;
        [_topCurView.layer setBorderWidth:2.0];
        _topCurView.alpha = 0.7;
        
        //[_topScanScrollView.scrollView addSubview:_topCurView];
        
    }
    
    return _mubanView;
}


- (UIView *)imageChangeView
{
    if (_imageChangeView == nil) {
        _imageChangeView = [[UIView alloc] initWithFrame:CGRectMake(0, BPScreenH, BPScreenW, buttomToolH)];
        _imageChangeView.backgroundColor = [UIColor blackColor];
        
        _imageScrollview = [[SwipeView alloc] initWithFrame:_imageScrollview.bounds];
        _imageScrollview.delegate = self;
        _imageScrollview.dataSource = self;
        [_imageChangeView addSubview:_imageScrollview];
        
        _customToolBar = [[customViewToolBar alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 70)];
        _customToolBar.delegate = self;
        [_imageChangeView addSubview:_customToolBar];
        
    }
    return _imageChangeView;
}


#pragma - mark点击底部按钮弹出的更换底纹view
- (UIView *)backShading
{
    if (_backShading == nil) {
        _backShading = [[UIView alloc] initWithFrame:CGRectMake(0, BPScreenH, BPScreenW, buttomToolH)];
        _backShading.backgroundColor = [UIColor blackColor];
        
        _shadingArry = [[NSUserDefaults standardUserDefaults] objectForKey:@"shading"];
        _shadingScrollview = [[SwipeView alloc] initWithFrame:_backShading.bounds];
        _shadingScrollview.backgroundColor = [UIColor clearColor];
        _shadingScrollview.delegate = self;
        _shadingScrollview.dataSource = self;
        [_backShading addSubview:_shadingScrollview];
        
        // 粉色的 框框 (不要了)
        _currentView = [[UIView alloc] init];
        [_currentView.layer setCornerRadius:5.0];
        [_currentView.layer setBorderColor:[BPGlobaThemeColor CGColor]];
        [_currentView.layer setBorderWidth:2.0];
        //[_shadingScrollview.scrollView addSubview:_currentView];
    }
    return _backShading;
}

#pragma mark - 设置底部点击弹出更换底色的view
- (UIView *)backViewColor
{
    if (_backViewColor == nil) {
        _backViewColor = [[UIView alloc] initWithFrame:CGRectMake(0, BPScreenH, BPScreenW, buttomToolH)];
        _backViewColor.backgroundColor = [UIColor blackColor];
        //数据源
        _colorArry = [[NSUserDefaults standardUserDefaults] objectForKey:@"backColor"];

        //设置ui
        _bgColorScrollview = [[SwipeView alloc] initWithFrame:_backViewColor.bounds];
        _bgColorScrollview.backgroundColor = [UIColor clearColor];
        _bgColorScrollview.delegate = self;
        _bgColorScrollview.dataSource = self;
        [_backViewColor addSubview:_bgColorScrollview];
        
    }
    return _backViewColor;
}

#pragma - mark 底部按钮点击事件----换底纹和换背景色
//换背景颜色
- (void)changeDiyBackViewColor:(UIButton *)colotBtn
{
//    if (_btnView.x != colotBtn.x || _btnView.y != colotBtn.y) {
        _btnView.frame = colotBtn.frame;
//    }
    
    NSInteger i = colotBtn.tag - 2000;
    _userEnableView.backgroundColor = colotBtn.backgroundColor;
    self.pageInfo.bg_color = _colorArry[i];
}

//换底纹
- (void)changeDiyBackShadingImage:(NSInteger)index
{
//    [BPImageTool setUpHDImageView:_userEnableView.shadingView1 addNsstringUrl:_shadingArry[index]];
    NSLog(@"--------------------%@",[[NSUserDefaults standardUserDefaults]objectForKey:@"SCALE"]);
    NSString *string = [[NSUserDefaults standardUserDefaults]objectForKey:@"SCALE"];
    float SCC =100 * [string floatValue];
    NSLog(@"%f",SCC);
    
    //    [BPImageTool getNSStringURL:[NSString stringWithFormat:@"%@?imageMogr2/thumbnail/!%fp",_shadingArry[index],SCC] setImageView:_userEnableView.shadingView1];
    
    
    
    for (int i = 0;  i  < _userEnableView.numXY ; i++) {
        for (UIView *ii in _userEnableView.subviews) {
            if (ii.tag == (500 + i)) {
                //[BPImageTool getNSStringURL:[NSString stringWithFormat:@"%@?imageMogr2/thumbnail/!%fp",_shadingArry[index],SCC] setImageView:(UIImageView *)ii];
                [BPImageTool getNSStringURL:_shadingArry[index] setImageView:(UIImageView *)ii];
            }
        }
    }
    self.pageInfo.shading = _shadingArry[index];
}

- (void)keyBoardShow;
{
    _toolBar.importText.text = _senderText.text;
    [_toolBar.importText becomeFirstResponder];
    
    CGRect frame = [self showFullScreen:_senderText];
    int offsetY = frame.origin.y + frame.size.height - (self.view.frame.size.height - self.keyboardView.height-_toolBar.height);
    if (offsetY > 0) {
        [UIView animateWithDuration:0.3f animations:^{
            self.centerView.y = -offsetY;
        }];
    }
    [UIView commitAnimations];
}

#pragma mark - ui动画效果（显示与消失）
- (void)buttomTableViewappear:(UIView *)view setY:(CGFloat)viewH
{
    [UIView animateWithDuration:0.5 animations:^{
        view.y = BPScreenH - buttomH - buttomToolH;
        if (view == self.keyboardView) {
            if (_senderText.height != 0) {
                self.centerView.y = viewH - _senderText.y - _senderText.height - _topScanScrollView.height;
            }
        }
    }];
}

- (void)buttomTableViewDisappear
{
    [UIView animateWithDuration:0.3 animations:^{
        _mubanView.y = BPScreenH;
        _backShading.y = BPScreenH;
        _backViewColor.y = BPScreenH;
        _imageChangeView.y = BPScreenH;
    }];
}

- (void)zidingyiJIanpanDisappear
{
    [self.view endEditing:YES];
    [UIView animateWithDuration:0.3 animations:^{
        self.centerView.y = 0;
        _keyboardView.y = BPScreenH;
    }];
}
- (void)fadeViewIn:(BPHeartMakeCenterView *)popupView
{
    popupView.alpha = 0.0f;
    
    [UIView animateWithDuration:1.0 animations:^{
        popupView.alpha = 1.0f;
    } completion:^(BOOL finished) {
    }];
}

#pragma - mark 左滑和右滑动画
- (void)rightAnimation
{
    _userEnableView.x = _userEnableView.x - BPScreenW;
    
    [UIView animateWithDuration:0.3f animations:^{
        
        _userEnableView.x = _userEnableView.x + BPScreenW;
    }];
}

- (void)leftAnimation
{
    _userEnableView.x = _userEnableView.x + BPScreenW;
    [UIView animateWithDuration:0.3f animations:^{
        
        _userEnableView.x = _userEnableView.x - BPScreenW;
        
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
